package cn.edu.tju.elm.service;

import cn.edu.tju.core.model.User;
import cn.edu.tju.core.security.service.UserService;
import cn.edu.tju.elm.model.Business;
import cn.edu.tju.elm.model.Cart;
import cn.edu.tju.elm.model.DeliveryAddress;
import cn.edu.tju.elm.model.Order;
import cn.edu.tju.elm.repository.BusinessRepository;
import cn.edu.tju.elm.repository.CartRepository;
import cn.edu.tju.elm.repository.DeliveryAddressRepository;
import cn.edu.tju.elm.repository.OrderRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class OrderService {

    @Autowired
    private OrderRepository orderRepository;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private BusinessRepository businessRepository;
    
    @Autowired
    private DeliveryAddressRepository deliveryAddressRepository;
    
    @Autowired
    private CartRepository cartRepository;

    /**
     * 创建新订单
     * @param order 订单信息
     * @return 保存后的订单
     */
    public Order createOrder(Order order) {
        // 自动填充customer信息
        if (order.getCustomer() == null) {
            User currentUser = userService.getUserWithAuthorities().orElse(null);
            if (currentUser != null) {
                order.setCustomer(currentUser);
            } else {
                throw new IllegalArgumentException("用户未认证或不存在");
            }
        }
        
        // 填充business信息
        if (order.getBusiness() != null && order.getBusiness().getId() != null) {
            Optional<Business> businessOpt = businessRepository.findById(order.getBusiness().getId());
            if (businessOpt.isPresent()) {
                order.setBusiness(businessOpt.get());
            } else {
                throw new IllegalArgumentException("指定的商家不存在");
            }
        } else {
            throw new IllegalArgumentException("商家不能为空");
        }
        
        // 填充deliveryAddress信息
        if (order.getDeliveryAddress() != null && order.getDeliveryAddress().getId() != null) {
            Optional<DeliveryAddress> addressOpt = deliveryAddressRepository.findById(order.getDeliveryAddress().getId());
            if (addressOpt.isPresent()) {
                order.setDeliveryAddress(addressOpt.get());
            } else {
                throw new IllegalArgumentException("指定的配送地址不存在");
            }
        } else {
            throw new IllegalArgumentException("配送地址不能为空");
        }
        
        // 计算订单总金额（从购物车计算）
        if (order.getOrderTotal() == null && order.getCustomer() != null && order.getBusiness() != null) {
            BigDecimal total = calculateOrderTotal(order.getCustomer().getId(), order.getBusiness().getId());
            if (total.compareTo(BigDecimal.ZERO) <= 0) {
                throw new IllegalArgumentException("购物车为空，无法创建订单");
            }
            order.setOrderTotal(total);
        }
        
        // 设置订单创建时间
        order.setOrderDate(LocalDateTime.now());
        // 初始状态设为1（待支付）
        if (order.getOrderState() == null) {
            order.setOrderState(1);
        }
        return orderRepository.save(order);
    }
    
    /**
     * 计算订单总金额
     * @param customerId 客户ID
     * @param businessId 商家ID
     * @return 订单总金额
     */
    private BigDecimal calculateOrderTotal(Long customerId, Long businessId) {
        List<Cart> cartItems = cartRepository.findAll().stream()
                .filter(cart -> cart.getCustomer() != null && cart.getCustomer().getId().equals(customerId)
                        && cart.getBusiness() != null && cart.getBusiness().getId().equals(businessId))
                .collect(Collectors.toList());
        
        BigDecimal total = BigDecimal.ZERO;
        for (Cart cart : cartItems) {
            if (cart.getFood() != null && cart.getFood().getFoodPrice() != null && cart.getQuantity() != null) {
                BigDecimal itemTotal = cart.getFood().getFoodPrice().multiply(BigDecimal.valueOf(cart.getQuantity()));
                total = total.add(itemTotal);
            }
        }
        return total;
    }

    /**
     * 根据ID获取订单
     * @param id 订单ID
     * @return 订单信息
     */
    public Optional<Order> getOrderById(Long id) {
        return orderRepository.findById(id);
    }

    /**
     * 根据用户ID获取订单列表
     * @param userId 用户ID
     * @return 订单列表
     */
    public List<Order> getOrdersByUserId(Long userId) {
        // 使用JPA查询所有订单，然后过滤出指定用户的订单
        return orderRepository.findAll().stream()
                .filter(order -> order.getCustomer() != null && order.getCustomer().getId().equals(userId))
                .collect(Collectors.toList());
    }

    /**
     * 更新订单状态
     * @param id 订单ID
     * @param orderState 新的订单状态
     * @return 更新后的订单
     */
    public Order updateOrderState(Long id, Integer orderState) {
        Optional<Order> orderOpt = orderRepository.findById(id);
        if (orderOpt.isPresent()) {
            Order order = orderOpt.get();
            order.setOrderState(orderState);
            return orderRepository.save(order);
        }
        return null;
    }

    /**
     * 删除订单
     * @param id 订单ID
     * @return 是否删除成功
     */
    public boolean deleteOrder(Long id) {
        if (orderRepository.existsById(id)) {
            orderRepository.deleteById(id);
            return true;
        }
        return false;
    }
}